Skip to content


ai  101  pytorch  classification  nvidia  cuda  install  tensorrt  yolo  ardupilot  None  ros2  dds  micro ros  xrce  sitl  plugin  SITL  debug  rangefinder  pymavlink  mavros  gazebo  distance sensor  system_time  timesync  cmake  gtest  ctest  cpp  c++  format  fmt  multithreading  spdlog  camera  coordinate system  orb  matching  opencv  build  transformation  computer vision  homography  optical flow  of  trackers  cv  cyclonedds  eprosima  fastdds  simulation  config  ignition  bridge  sdf  tips  ign-transport  sensors  lidar  aptly  apt  encryption  pgp  docker  git  bundle  submodules  github  hooks  pre-commit  lxd  container  lxc  x11  profile  vscode  marpit  presentation  marp  markdown  mermaid  video  ffmpeg  gstreamer  cheat-sheet  sdp  v4l2loopback  gi  snippets  cheat Sheet  python  asyncio  future  click  cli  numpy  project  template  black  isort  docs  project document  docstrings  flake8  linter  git-hook  mypy  unittest  pytest  pylint  from a-z  mock  iterator  generator  logging  tuple  namedtuple  typing  annotation  typever  pyzmq  zmq  msgpack  action  namespace  remap  control2  ros2_control  gdb  qos  tag  plugins  msg  node  zero-copy  shm  tutorial  algorithm  calibration  diff  pid  dev  colcon  colcon_cd  rpi  arm  qemu  settings  behavior  plot  visualization  debugging  diagnostic  diagnostics  tutorials  gst  math  apm  rat_runtime_monitor  web  rosbridge  vue  binding  discovery  gazebo-classic  launch  spawn  cook  gps  imu  ray  gazebo_ros_ray_sensor  ultrsonic  range  ultrasonic  gazebo classic  wrench  effort  odom  ign  gz  xacro  ros_ign  diff_drive  odometry  joint_state  argument  OpaqueFunction  DeclareLaunchArgument  LaunchConfiguration  tmux  nav  slam  test  rclpy  action client  custom messages  executor  MultiThreadedExecutor  SingleThreadedExecutor  param  dynamic-reconfigure  service  client  setup.py  package.xml  parameter  parameters  custom  msgs  executers  pub  sub  rqt  rviz  rviz2  pose  marker  tf2  deb  package  setup  local_setup  rosdep  package manager  project settings  vcstool  cross-compiler  nano  texture  tmuxp  rootfs  embedded  zah  linux  rm  ubuntu  sudo  sudoers  nopasswd  visudo  udev  ip  ss  network  netstat  snap  deploy  ssh  systemd  mkdocs  extensions  socat  networking  serial  udp  tc  mtu  select  px4  robotics  kalman_filter  kalman  filter  control  todo  vscode-ext  json  yaml  schema  yocto  poky  world  gazebo_ros2_control  position_controller  effort_controller  velocity_controller  urdf  gazebo_ros_force  gazebo_ros_joint_state_publisher  robot_state_publisher  joint_state_publisher  projects  vrx  buoyancy 

PyTest - Mocking


mocking

A mock object is a simulated object that mimics the behavior of the smallest testable parts of an application in controlled ways. It’s replace of one or more function or objects calls

A mock function call return a predefined value immediately without doing any work

In Python mocking implement by unittest.mock module

Simple demo#

project
search
  ├── tutorial
  │ ├── __init__.py
  │ └── demo.py
  └── tests
   └── test_demo.py
demo.py
# method to mock
def get_number() -> int:
    return 5

# function under test
def add(a: int) -> int:
    b = get_number()
    return a + b
test_demo.py
from unittest.mock import patch, MagicMock

@patch("tutorial.demo.get_number")
def test_add_mock(mock_get_number: MagicMock) -> None:
    mock_get_number.return_value = 2
    result = add(1)
    assert result == 3

Warning

@path full name of the function or class to patch module_name.func_name for example to path get_number function in demo module. @patch("demo.get_number")


MagicMock#

Provide a simple mocking interface that allow to mock partial real object that we wont to patch

return_value#

allows you to choose what the patched callable returns, usually we return the same type of the real callable but controllable

side_effect#

Change the behavior of the mock

side_effect = Iterable#

yield the values from defined iterable on subsequent call

>>> from unittest.mock import MagicMock
>>> m = MagicMock()
>>> m.get_data.side_effect = [5, 10, 15]
>>> m.get_data()
5
>>> m.get_data()
10
>>> m.get_data()
15
from unittest.mock import patch

def my_input() -> int:
    return 1

def method_to_test():
    a = my_input()
    b = my_input()
    return a+b


@patch("test_demo.my_input")
def test_multiple(mock_my_input):
    mock_my_input.side_effect = [1, 2]
    result = method_to_test()
    assert result == 3
side_effect = Exception#
m.check.side_effect = Exception("custom exception")
>>> m.check()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python3.8/unittest/mock.py", 
  ...
    raise effect
Exception: custom exception
ide_effect = callable#

The callable will be executed on each call with the parameters passed when calling the mocked method

>>> def call_me(name):
...     print(name)
... 
>>> m.run_call.side_effect = call_me
>>> m.run_call("a")
a
>>> m.run_call("b")
b
>>> m.run_call.call_count
2
>>> m.run_call("b")
b
>>> m.run_call.call_count
3

Reference#